import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCourseStore = defineStore('course', () => {
  // 课程列表
  const courses = ref([])
  const currentCourse = ref(null)
  const currentChapter = ref(null)
  const learningProgress = ref({})
  
  // 获取课程列表
  const getCourses = computed(() => courses.value)
  
  // 获取当前课程
  const getCurrentCourse = computed(() => currentCourse.value)
  
  // 获取当前章节
  const getCurrentChapter = computed(() => currentChapter.value)
  
  // 获取学习进度
  const getLearningProgress = computed(() => learningProgress.value)
  
  // 设置课程列表
  const setCourses = (data) => {
    courses.value = data
  }
  
  // 设置当前课程
  const setCurrentCourse = (course) => {
    currentCourse.value = course
  }
  
  // 设置当前章节
  const setCurrentChapter = (chapter) => {
    currentChapter.value = chapter
  }
  
  // 设置学习进度
  const setLearningProgress = (progress) => {
    learningProgress.value = progress
  }
  
  // 更新课程进度
  const updateCourseProgress = (courseId, progress) => {
    if (!learningProgress.value[courseId]) {
      learningProgress.value[courseId] = {}
    }
    learningProgress.value[courseId] = { ...learningProgress.value[courseId], ...progress }
    localStorage.setItem('learningProgress', JSON.stringify(learningProgress.value))
  }
  
  // 从本地存储加载进度
  const loadProgressFromStorage = () => {
    const stored = localStorage.getItem('learningProgress')
    if (stored) {
      learningProgress.value = JSON.parse(stored)
    }
  }
  
  return {
    courses,
    currentCourse,
    currentChapter,
    learningProgress,
    getCourses,
    getCurrentCourse,
    getCurrentChapter,
    getLearningProgress,
    setCourses,
    setCurrentCourse,
    setCurrentChapter,
    setLearningProgress,
    updateCourseProgress,
    loadProgressFromStorage
  }
})